<?php 
	class Surveys{
		public function __construct(){
			FunctionsHelper::includeFiles(
				array(
					PUBLIC_MODELS_DIRECTORY . 'model.php',
					PUBLIC_MODELS_DIRECTORY . 'survey.php'
				)
			);
		}
		
		public function getLast(){
			$LastSurvey = new Survey();
			$LastSurvey->getLastSurvey();
			$votes = $LastSurvey->getNumberVotes();
			$LastSurvey->setTotalVotes($votes[0]['total']);
			$LastSurvey->getMyOptions();

			$Options = $LastSurvey->getOptions();
			foreach ($Options as &$Option){
				$TotalVotes = $LastSurvey->answers($Option->id, $LastSurvey->getId());
				$Option->Total = !empty($TotalVotes) && $TotalVotes[0]["total"] > 0 ? $TotalVotes[0]["total"] : 0;
			}
			//$LastSurvey->setOptions($this->getVotes($LastSurvey));
			return $LastSurvey;
		}
		
		private function getVotes($survey){
			
			$votes = $survey->getVotes();
			$total = $this->_getTotal($votes);
			foreach ($votes as &$vote){
				$vote["porcentaje"] = round(($vote["votos"]*100/$total), 2);
			}

			return $votes;
		}
		
		public function getActive(){
			$SurveyM = new Survey();
			
			$surveyArr = $SurveyM->getCurrent();
			
			if (empty($surveyArr))
				return new Survey();
			
			$Survey = new Survey($surveyArr[0]);
			$Survey->getMyOptions();
			return $Survey;
		}

		public function Vote($survey, $option){
			$survey = new Survey(
				array(
					'id' => $survey
				)
			);
			
			if (!$survey->userHasVoted($_SERVER["REMOTE_ADDR"]))
				$survey->Vote($option, $_SERVER["REMOTE_ADDR"]);
				
		}

		private function _getTotal($votes){
			$total = 0;
			foreach ($votes as $vote){
				$total += $vote["votos"];
			}

			return $total;
		}

	}

?>